<template>
  <div id="app">

    <el-form :inline="true" style="margin-top: -50px;margin-left: 20px;">
      <el-form-item label="商品名">
        <el-input
          style="width: 70%;"
          placeholder="请输入关键词"
          prefix-icon="el-icon-search"
          v-model="keyword"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="商品状态" style="margin-left: -70px;">
        <el-select v-model="status" placeholder="请选择商品竞拍状态" style="width: 80%;">
          <!-- 状态（0.未拍出，1.正在拍卖，2.已拍出） -->
          <el-option label="全部" value="-1"></el-option>
          <el-option label="未拍出" value="0"></el-option>
          <el-option label="正在拍卖" value="1"></el-option>
          <el-option label="已拍出" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: -50px;">
        <el-button icon="el-icon-search" circle @click="initProductList()"></el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="dialog = true" round
    style="float: right;margin-top: -60px;margin-right: 20px">
      添加拍卖品
    </el-button>

    <el-drawer
      title="添加拍卖品"
      :before-close="handleClose"
      :visible.sync="dialog"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      >
      <div class="demo-drawer__content">

        <el-form>
          <el-form-item label="商品名" :label-width="formLabelWidth">
            <el-input v-model="productName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品介绍" :label-width="formLabelWidth">
            <el-input v-model="productDetail" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>

       <el-upload
        		class="upload-demo"
        		ref="uploadImport"
            :http-request="httpRequest"
            action=""
        		accept="image/jpeg,image/gif,image/png,image/jpg"
        		:before-upload="onBeforeUpload"
        		:on-preview="handlePreview"
        		:on-remove="handleRemove"
        		:on-change="handleChange"
        		:file-list="fileList"
            :auto-upload="false"
        		list-type="picture">
        	<el-button size="small" type="primary">点击上传</el-button>
        	<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1MB</div>
        </el-upload>


        <div class="demo-drawer__footer" style="display: flex;">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>


    <el-row>
      <el-col :span="6" v-for="(p,pIndex) in productList" :key="p.id" style="margin-bottom: 20px;">
        <el-col :span="22" style="margin-left: 20px;">
          <el-card>
            <div style="height: 200px;overflow-y:auto;position: relative;">
              <el-image :key="p.productImgList[0]" :src="p.productImgList[0]"
                  :preview-src-list="p.productImgList"></el-image>
                  <div v-if="p.status==2" style="position:absolute;bottom: 50px;right: 10px;border: 3px solid #fff9;border-radius:5px;font-size: 25px;background-color: #fff9;box-shadow: inset 0 0 0 3px #666;padding:5px 10px;transform: rotate(-10deg);">已拍出</div>
            </div>
            <div>商品名：{{p.productName}}</div>
            <div>介绍：{{p.productDetail}}</div>

            <!-- 创建竞拍||开始竞拍 对话框 -->
            <!-- product（0.未拍出，1.正在拍卖，2.已拍出） -->
            <!-- auction (0.未开始，1.进行中，2.已结束（拍出），3.流盘（未拍出）) -->
            <el-button type="primary" v-if="!p.auction && p.status==0" style="margin-top: 10px;" @click="openForm(p.id)">创建竞拍</el-button>
            <el-button type="primary" v-if="p.auction || p.status==2" style="margin-top: 10px;" disabled>创建竞拍</el-button>

            <el-dialog title="创建竞拍" :visible.sync="dialogFormVisible">
              <el-form :model="form">
                <el-form-item label="起拍价" :label-width="formLabelWidth">
                  <el-input v-model="form.basePrice" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="加价幅度" :label-width="formLabelWidth">
                  <el-input v-model="form.stepPrice" autocomplete="off"></el-input>
                </el-form-item>
                <!-- <div class="block">
                    <span class="demonstration" style="margin-left: 35px;">拍卖时长/天</span>
                    <el-date-picker
                      style="margin-left: 5px;"
                      v-model="twoDate"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :picker-options="setDateRange">
                    </el-date-picker>
                  </div> -->
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="toAddAuction()">确 定</el-button>
              </div>
            </el-dialog>

            <!-- 如果商品未拍出,可点击修改商品信息 -->
            <el-button v-if="p.status==0" type="text" @click="dialogFormVisible2 = true;productId = p.id;productName2 = p.productName;productDetail2 = p.productDetail;" style="float: right;margin-top: -50px;margin-right: 10px;">商品设置<i class="el-icon-setting el-icon--right"></i></el-button>
            <el-button v-if="p.status!=0" type="text" style="float: right;margin-top: -50px;margin-right: 10px;" disabled>商品设置<i class="el-icon-setting el-icon--right"></i></el-button>
            <!-- 点击查看历史竞拍 -->
            <el-button type="text" @click="dialogTableVisible = true;auctionList = p.auctionList;" style="float: right;margin-top: -30px;margin-right: 10px;">历史竞拍<i class="el-icon-date el-icon--right"></i></el-button>

            <!-- 如果正在竞拍,可点击进入拍卖场 -->
            <div v-if="p.auction" style="float: right;margin-top: 15px;margin-right: -90px;"><router-link :to="{name: 'Ces', query: {id:p.auction.id, productId: p.id }}"  >拍卖进行中<i class="el-icon-loading el-icon--right"></i></router-link></div>

            <!-- 如果商品已拍出,显示已结束 -->
            <div v-if="p.status==2" style="float: right;margin-top: 15px;margin-right: -90px;"><el-link type="primary" disabled>已卖出</el-link></div>


            <el-dialog title="商品信息设置" :visible.sync="dialogFormVisible2">
              <el-form>
                <el-form-item label="商品名" :label-width="formLabelWidth">
                  <el-input v-model="productName2" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品介绍" :label-width="formLabelWidth">
                  <el-input v-model="productDetail2" autocomplete="off"></el-input>
                </el-form-item>
              </el-form>
              <el-upload
               		class="upload-demo"
               		ref="uploadImport"
                   :http-request="toUpdate"
                   action=""
               		accept="image/jpeg,image/gif,image/png,image/jpg"
               		:before-upload="onBeforeUpload2"
               		:on-preview="handlePreview2"
               		:on-remove="handleRemove2"
               		:on-change="handleChange2"
               		:file-list="fileList2"
                   :auto-upload="false"
               		list-type="picture">
               	<el-button size="small" type="primary">点击上传</el-button>
               	<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1MB</div>
               </el-upload>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="toUpdate()">修 改</el-button>
              </div>
            </el-dialog>

            <el-dialog title="历史竞拍" :visible.sync="dialogTableVisible" width="80%">
              <el-table :data="auctionList" @row-click="toAuction">
                <el-table-column property="id" label="竞拍室id" width="180"></el-table-column>
                <el-table-column property="basePrice" label="起拍价" width="80"></el-table-column>
                <el-table-column property="stepPrice" label="加价幅度" width="80"></el-table-column>
                <el-table-column property="nickname" label="最高竞价持有者" width="100"></el-table-column>
                <el-table-column property="topPrice" label="最高竞价" width="80"></el-table-column>
                <el-table-column property="createTime" label="创建时间" width="190"></el-table-column>
                <el-table-column property="startTime" label="竞拍开始时间" width="190"></el-table-column>
                <el-table-column property="auctionTime" label="拍卖时长/天"></el-table-column>
                <el-table-column property="status" label="状态" width="200">
                  <template slot-scope="scope">
                    <span v-if="scope.row.status==0">未开始</span>
                    <span v-if="scope.row.status==1">进行中</span>
                    <span v-if="scope.row.status==2">已结束（拍出）</span>
                    <span v-if="scope.row.status==3">流盘（未拍出）</span>
                  </template>
                </el-table-column>
                <el-table-column property="joinCount" label="参与人数"></el-table-column>
              </el-table>
            </el-dialog>

          </el-card>
        </el-col>
      </el-col>
    </el-row>

    <el-pagination
      style="text-align: center;"
      @current-change="initProductList"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      layout="prev, pager, next, jumper"
      :total="totalPage">
    </el-pagination>

  </div>
</template>

<style>
  .el-drawer__header {
    align-items: center;
    color: #72767b;
    display: flex;
    margin-bottom: 32px;
    padding: 20px 20px 0;
  }
  .el-drawer__body {
    padding: 20px;
    flex: 1;
    overflow: auto;
  }
  .demo-drawer__content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .demo-drawer__content form {
      flex: 1;
  }
  .demo-drawer__footer button {
    flex: 1
  }
  .upload-demo {
    flex: 1;
  }

</style>

<script>
import qs from "qs";
import router from "../router";
  export default {
    name: 'ProductView',
    data() {
      return {

        dialog: false,
        loading: false,

        productName: '',
        productDetail: '',
        formLabelWidth: '120px',
        timer: null,
        productName2: '',
        productDetail2: '',

        fileList: [],
        fileList2: [],

        productList: [],
        currentPage:1,
        pageSize:8,
        totalPage: 0,
        keyword:'',
        status:'',

        dialogTableVisible: false,
        auctionList: [],
        dialogFormVisible: false,
        dialogFormVisible2: false,
        //此id用于商品修改
        productId:'',

        // twoDate: '',
        // //设置时间区间限制
        // setDateRange: {
        // 	disabledDate: time => {
        // 		// 只能选择当前 1 年内的时间
        // 		const year = 365 * 24 * 3600 * 1000;
        // 		// 只能选择当前 1 月的时间
        // 		const month = 30 * 24 * 3600 * 1000;
        // 		// 只能选择当前 1 周的时间
        // 		const week = 7 * 24 * 3600 * 1000;
        // 		// 只能选择当前 1 天的时间
        // 		const day = 24 * 3600 * 1000;
        // 		// 返回小于当前日期并近【1年】【1月】【1周】内的日期
        // 		// 注意：这是从当前日期开始往前算，如果当前日期可选的话，不要写【-8.64e7】
        // 		return time.getTime() > Date.now() + 2 * week || time.getTime() < (Date.now() - 8.64e7) + day;
        // 	}
        // },
        form: {
          productId: '',
          basePrice: '',
          stepPrice: '',
          // auctionTime: '',
        },
      }
    },
    methods: {
      initProductList(){
        let params={
          currentPage:this.currentPage,
          pageSize:this.pageSize,
          keyword:this.keyword,
          status:this.status
        }
        this.axios.post("/moon-service-auction/product/select", qs.stringify(params))
        .then(res => {
          this.productList = res.list;
          this.totalPage = res.total;
        })
      },
      toAuction(raw) {
        if(raw.status==1){
          this.$confirm('竞拍正在进行中, 是否进入?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            this.$router.push({
              name:'Ces',
              query:{
                id:raw.id,
                productId:raw.productId
              }
            })
          }).catch(() => {
          });
        }
      },
      //打开对话框
      openForm(pId){
        this.dialogFormVisible = true;
        this.form.productId = pId;
      },
      toAddAuction(){
        if(this.form.basePrice=='' || this.form.stepPrice==''){
          this.$message({
            message: '不能为空',
            type: 'warning'
          })
          return;
        };
        if(!this.isnum(this.form.basePrice) || !this.isnum(this.form.stepPrice)){
          this.$message({
            message: '必须填正数',
            type: 'warning'
          })
          return;
        };

        this.dialogFormVisible = false;
        // let twoDate = this.twoDate;
        // let con = twoDate[1] - twoDate[0];
        // this.form.auctionTime = con/ (1 * 24 * 60 * 60 * 1000);
        this.axios.post("/moon-service-auction/auction/insert", qs.stringify(this.form))
        .then(res => {
          if(res=='success'){
            this.$message({
              message: '竞拍室创建成功',
              type: 'success'
            });
            this.initProductList();
          }
        })
      },
      //抽屉部分
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定要提交表单吗？')
          .then(_ => {
            //触发httpRequest方法,实现手动上传

            if(!this.productName || !this.productDetail) {
              this.$message({
                message: '不能为空',
                type: 'warning'
              })
              return;
            }
            if(this.fileList.length == 0) {
              this.$message({
                message: '未上传图片',
                type: 'warning'
              })
              return;
            }

            this.$refs.uploadImport.submit();

            this.loading = true;
            this.timer = setTimeout(() => {
              done();
              // 动画关闭需要一定的时间
              setTimeout(() => {
                this.loading = false;
              }, 400);
            }, 2000);
          })
          .catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.dialog = false;
        clearTimeout(this.timer);
      },

      // 图片上传部分
      handleRemove(file, fileList) {
      	this.fileList = fileList.filter(item => item !== file)
      },
      handlePreview(file) {
      },
      handleChange(file) {
        this.fileList.push(file);
      },
      httpRequest(param) {
        console.log("提交!!")

        let formData = new FormData();
        let fileList = this.fileList;

        fileList.forEach((n)=>{
          formData.append("fileList",n.raw);
        });
        formData.append("productName", this.productName);
        formData.append("productDetail", this.productDetail)

        //提交
        formData.forEach((n)=>{
          console.log(n)
        })

        let _this = this;
        this.axios.post("/moon-service-auction/product/insert", formData, {
          "Content-Type": "multipart/form-data;charset=utf-8",
          })
          .then(res => {
            if (res == "success") {
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 1000,
              });
              //清空数据
              this.fileList = [];
              this.productName = '';
              this.productDetail = '';
              this.initProductList();
            }
          })
      },
      onBeforeUpload(file) {
      	const isIMAGE = file.type === 'image/jpeg'||'image/gif'||'image/png'||'image/jpg';
      	const isLt1M = file.size / 1024 / 1024 < 1
      	if (!isIMAGE) {
      		this.$message.error('上传文件只能是图片格式!');
      	}
      	if (!isLt1M) {
      		this.$message.error('上传文件大小不能超过 1MB!');
      	}
      	return isIMAGE && isLt1M;
      },
      // 图片上传部分2
      handleRemove2(file, fileList) {
      	this.fileList2 = fileList.filter(item => item !== file)
      },
      handlePreview2(file) {
      },
      handleChange2(file) {
        this.fileList2.push(file);
      },
      toUpdate() {
        console.log("提交!!")
        if(!this.productName2 || !this.productDetail2) {
          this.$message({
            message: '不能为空',
            type: 'warning'
          })
          return;
        }
        let formData = new FormData();
        let fileList = this.fileList2;

        fileList.forEach((n)=>{
          formData.append("fileList",n.raw);
        });
        formData.append("id", this.productId);
        formData.append("productName", this.productName2);
        formData.append("productDetail", this.productDetail2)

        //提交
        formData.forEach((n)=>{
          console.log(n)
        })

        this.axios.post("/moon-service-auction/product/update", formData, {
          "Content-Type": "multipart/form-data;charset=utf-8",
          })
          .then(res => {
            this.dialogFormVisible2 = false;
            if (res == "success") {
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 1000,
              });
              this.initProductList();
            }
          })
      },
      onBeforeUpload2(file) {
      	const isIMAGE = file.type === 'image/jpeg'||'image/gif'||'image/png'||'image/jpg';
      	const isLt1M = file.size / 1024 / 1024 < 1
      	if (!isIMAGE) {
      		this.$message.error('上传文件只能是图片格式!');
      	}
      	if (!isLt1M) {
      		this.$message.error('上传文件大小不能超过 1MB!');
      	}
      	return isIMAGE && isLt1M;
      },
      //校验方法
      //是否为数字
      isnum(n){
      	let reg=/^[1-9]\d*(\.\d+)?$/;
      	return reg.test(n);
      },
    },
    created() {
      this.initProductList();
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
